package com.example.beatx.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Controller
public class ImageController {

    @GetMapping("/download/{imageName}")
    public ResponseEntity<FileSystemResource> post(@PathVariable("imageName") String imageName) {
        System.out.println("download/"+imageName);
        String imagePath = "C:\\Users\\YE\\Desktop\\imgs\\" + imageName;
        File file = new File(imagePath);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        MediaType mediaType = MediaType.ALL;
        String type=imageName.substring(imageName.lastIndexOf('.')+1).toLowerCase();
        if(type.equals("png"))mediaType=MediaType.IMAGE_PNG;
        else if(type.equals("jpg"))mediaType=MediaType.IMAGE_JPEG;
        return ResponseEntity.ok()
                .contentType(mediaType)
                .body(new FileSystemResource(file));
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestPart("file") MultipartFile file) throws IOException {
        System.out.println("upload/"+file.getOriginalFilename());
        InputStream ins=file.getInputStream();
        BufferedInputStream bi=new BufferedInputStream(ins);
        FileOutputStream out=new FileOutputStream(new File("C:\\Users\\YE\\Desktop\\imgs\\"+file.getOriginalFilename()));
        byte[] buffer=new byte[1024];
        int length=-1;
        while((length=bi.read(buffer))!=-1){
            out.write(buffer,0,length);
        }
        out.flush();
        ins.close();
        bi.close();
        out.close();
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body("Success");
    }
}
